package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private SeckillVoucherServiceImpl seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }


    // 只会被一个线程执行的任务
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    // TODO 订单阻塞队列在内存中 存在数据不安全问题  使用redis消息队列解决
    // TODO　JVM的阻塞队列 阻塞队列内存限制问题 设置了1024 * 1024的长度限制 如果订单过多放不下怎么办
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    @PostConstruct
    private void initVoucherOrderTasks() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    //    private class VoucherOrderHandler implements Runnable {
//        @Override
//        public void run() {
//            while ( true){
//                try {
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    // 创建订单
//                    handleVoucherOrder(voucherOrder);
//                } catch (InterruptedException e) {
//                    log.error("处理订单异常", e);
//                }
//            }
//        }
//    }


    // 基于 redis  stream的redis队列处理任务 解决使用jvm BlockingQueue 阻塞队列内存限制问题 和 内存数据易失问题
    private class VoucherOrderHandler implements Runnable {

        String MQ_NAME = "stream.orders";

        @Override
        public void run() {
            while (true) {
                try {
                    // XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS streams.order >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(MQ_NAME, ReadOffset.lastConsumed())
                    );
                    if (CollectionUtil.isEmpty(list)) {
                        // 获取失败
                        continue;
                    }
                    // 获取成功下单处理
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
//                    VoucherOrder voucherOrder = BeanUtil.mapToBean(value,  VoucherOrder.class, false);
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    handleVoucherOrder(voucherOrder);
                    // 获取订单后确认
                    stringRedisTemplate.opsForStream().acknowledge(MQ_NAME, "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    while (true) {
                        handlePendingList();
                    }
                }
            }
        }
    }

    private void handlePendingList() {
        while (true) {
            try {
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                        StreamOffset.create("streams.order", ReadOffset.from("0"))
                );
                if (CollectionUtil.isEmpty(list)) {
                    // 获取失败
                    break;
                }
                // 获取成功下单处理
                MapRecord<String, Object, Object> record = list.get(0);
                Map<Object, Object> value = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                handleVoucherOrder(voucherOrder);
                // 获取订单后确认
                stringRedisTemplate.opsForStream().acknowledge("streams.order", "g1", record.getId());
            } catch (Exception e) {
                log.error("处理pending-list订单异常", e);
                // 自己又出异常 会继续
                // 可以设置 休眠一会 给予缓冲时间
                try {
                    Thread.sleep(50);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        // 这部分其实不用加锁
        Long userId = voucherOrder.getUserId();
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            log.error("不允许重复下单");
            return;
        }
        try {
            // 一人一单 其实这里已经不用判断一人一单了 因为前面redis的lua脚本中已经判断过
            int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
            if (count >= 1) {
                log.error("您已经购买过一次了");
                return;
            }
            // 扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock = stock - 1")
                    .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0) // 乐观锁
                    .update();
            if (!success) {
                log.error("库存不足");
                return;
            }
            save(voucherOrder);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Result seckillVoucher(Long voucherId) throws InterruptedException {
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");
        Long res = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                String.valueOf(voucherId), String.valueOf(userId), String.valueOf(orderId));
        int i_res = res.intValue();
        if (i_res != 0) {
            return Result.fail(i_res == 1 ? "库存不足" : "不能重复下单");
        }
        // 返回订单id
        return Result.ok(orderId);
    }

    /*
        阻塞队列的方法
     */
    public Result seckillVoucher2(Long voucherId) throws InterruptedException {
        Long userId = UserHolder.getUser().getId();
        Long res = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                String.valueOf(voucherId), String.valueOf(userId));
        int i_res = res.intValue();
        if (i_res != 0) {
            return Result.fail(i_res == 1 ? "库存不足" : "不能重复下单");
        }
        // res == 0 保存到阻塞队列 以后获取队列中的数据处理
        long orderId = redisIdWorker.nextId("order");
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        // 写操作放到后面 异步写
        orderTasks.add(voucherOrder);
        // 返回订单id
        return Result.ok(orderId);
    }


    public Result seckillVoucher1(Long voucherId) throws InterruptedException {
        // 查询优惠卷
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if (voucher == null) {
            return Result.fail("优惠券不存在");
        }
        // 判断秒杀是否开始 判断秒杀是否结束
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始");
        }
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已结束");
        }
        // 库存检查
        if (voucher.getStock() < 1) {
            return Result.fail("库存不足");
        }
        Long userId = UserHolder.getUser().getId();

//        SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
        RLock lock = redissonClient.getLock("lock:order:" + userId);
//        synchronized (userId.toString().intern()) {
//            // 事务提交之后再去释放锁
//            // 需要拿到事务代理对象才可以 直接调用的createVoucherOrder不具有事务功能
//            IVoucherOrderService proxy = (IVoucherOrderService)AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId, userId);
//        }
        // 锁的超时时间
        // 使用订阅和信号量进行等待锁
        boolean isGet = lock.tryLock(-1, TimeUnit.SECONDS); // 使用了无参数的redission分布式锁
        if (!isGet) {
            return Result.fail("您已经提交过申请了");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId, userId);
        } finally {
            // 使用finally 释放锁
            // 分布式锁的误删问题 使用当前线程是否和解锁的线程一致
            lock.unlock();
        }
    }

    @Transactional
    public Result createVoucherOrder(Long voucherId, Long userId) {

        // 一人一单

        // 悲观锁 不加在方法上(因为会变成单线程执行) 利用userId的值加锁 intern()函数才行
        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count >= 1) {
            return Result.fail("您已经购买过一次了");
        }
        // 扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId).gt("stock", 0)
                //.gt("stock", 0) // where stock = stock 乐观锁
                .update();
        if (!success) {
            return Result.fail("库存不足");
        }
        // 创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);
        return Result.ok(orderId);
    }
}
